
package com.kugou.game.sdk.ui.activity;

import java.util.ArrayList;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;
import android.widget.TextView;

import com.kugou.game.sdk.adapter.MessageBaseAdater;
import com.kugou.game.sdk.adapter.MessageBaseAdater.OnDeleteClickListener;
import com.kugou.game.sdk.adapter.MessageBaseAdater.OnMessageItemClickListener;
import com.kugou.game.sdk.api.common.User;
import com.kugou.game.sdk.base.BaseCommonTitleFragmentActivity;
import com.kugou.game.sdk.core.SDKActions;
import com.kugou.game.sdk.core.SDKControler;
import com.kugou.game.sdk.core.UserManager;
import com.kugou.game.sdk.entity.MyMessage;
import com.kugou.game.sdk.interfaces.OnEditMessageListener;
import com.kugou.game.sdk.interfaces.OnLoadMessageListListener;
import com.kugou.game.sdk.statistics.StatCmd;
import com.kugou.game.sdk.statistics.StaticsManager;
import com.kugou.game.sdk.ui.widget.TipsLayout;
import com.kugou.game.sdk.utils.Rx;

/**
 * 描述:消息列表页面
 * 
 * @author liux
 * @since 2013-12-25 下午02:45:39
 */
public class MessageListActivity extends BaseCommonTitleFragmentActivity implements
        OnScrollListener, OnClickListener, OnDeleteClickListener, OnMessageItemClickListener {

    private Context context;

    private final int MESSAGE_DETAILREQUEST_CODE = 101;

    /**
     * 消息相关指令
     */
    private static final int MSG_REQUEST_MESSAGE_LIST = 0;

    private static final int MSG_REQUEST_MESSAGE_LIST_SUCCESS = 1;

    private static final int MSG_REQUEST_MESSAGE_LIST_FAILE = 2;

    private static final int MSG_SHOW_LOADING_VIEW = 3;

    private static final int MSG_BACK_REQUEST_DELETE = 4;

    private static final int MSG_UI_REQUEST_DELETE_SUCCESS = 5;

    private static final int MSG_UI_REQUEST_DELETE_FAILE = 6;

    private static final int MSG_UI_REQUEST_DELETE_START = 7;

    /**
     * 页面控件
     */
    private View layoutEmail;

    private TipsLayout mTipsLayout;

    private TextView tvLoadingWrong;

    private ListView mListView;

    private MessageBaseAdater adapter;

    private View footerView;

    private ProgressDialog progressDialog;

    /**
     * 第几页消息
     */
    private int pageIndex = 0;

    public static final int PAGE_SIZE = 20;

    private EmailReceiver receiver;

    private boolean mHasMoreData = true;

    private String mLastMessageUnixTime = "0";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;
        int layoutId = Rx.layout.kg_activity_message_list;
        setContentView(layoutId);
        // 设置标题
        setCommonTitle(Rx.string.kg_kugou_mail_message_activity);
        // 显示删除按钮
        setCommonRightImageViewVisibility(View.VISIBLE);
        setCommonRightImageResource(Rx.drawable.kg_img_delete);
        setCommonRightImgListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (adapter.isDeleteMode()) {
                    setCommonRightImageResource(Rx.drawable.kg_img_delete);
                    adapter.setDeleteMode(false);
                } else {
                    setCommonRightImageResource(Rx.drawable.kg_img_close);
                    adapter.setDeleteMode(true);
                }
                adapter.notifyDataSetChanged();
            }
        });
        initView();
        sendEmptyBackgroundMessage(MSG_REQUEST_MESSAGE_LIST);
        initReceiver();
        // 发送统计-进入我的消息列表
        StaticsManager.sendCommonStatis(StatCmd.CMD_BI_ENTER_MYNEWS);
    }

    private void initReceiver() {
        receiver = new EmailReceiver();
        IntentFilter filter = new IntentFilter(SDKActions.ACTION_READ_ONE_EMAIL);
        filter.addAction((SDKActions.ACTION_DELETE_ONE_UNREAD_EMAIL));
        registerReceiver(receiver, filter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }

    /**
     * 初始化界面
     */
    private void initView() {
        layoutEmail = findViewById(Rx.id.kg_layout_email);
        mListView = (ListView) findViewById(Rx.id.kg_listView);
        mListView.setOnScrollListener(this);
        mListView.addFooterView(getFooterView());
        adapter = new MessageBaseAdater(this, new ArrayList<MyMessage>());
        adapter.setOnDeleteClickListener(this);
        adapter.setOnMessageItemClickListener(this);
        mListView.setAdapter(adapter);

        progressDialog = new ProgressDialog(context);
        progressDialog.setMessage("正在加载");
        progressDialog.setCancelable(false);

        // tvLoadingWrong = (TextView) findViewById(Rx.id.tv_loading_wrong);
        mTipsLayout = (TipsLayout) findViewById(Rx.id.kg_tips_layout);
        mTipsLayout.setLoadingText("");
        mTipsLayout.setLoadingViewBackground(Rx.drawable.kg_gamecenter_loading);
        mTipsLayout.setOnRefreshButtonClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                pageIndex = 0;
                adapter.clearDatas();
                sendEmptyBackgroundMessage(MSG_REQUEST_MESSAGE_LIST);
            }
        });
    }

    @Override
    public void handleBackgroundMessage(final Message msg) {
        switch (msg.what) {
            case MSG_REQUEST_MESSAGE_LIST:
                sendEmptyUiMessage(MSG_SHOW_LOADING_VIEW);
                User user = UserManager.getInstance().getCurrentUserInternal();
                String Username = user.getAccountName();
                int gameid = SDKControler.getGameId();
                final Message message = new Message();
                UserManager.getInstance().getMessageList(Username, ++pageIndex, PAGE_SIZE,
                        mLastMessageUnixTime, new OnLoadMessageListListener() {
                            @Override
                            public void onSuccess(ArrayList<MyMessage> messages) {// 请求成功
                                message.what = MSG_REQUEST_MESSAGE_LIST_SUCCESS;
                                message.obj = messages;
                                sendUiMessage(message);
                            }

                            @Override
                            public void onFailed(String prompt) {// 请求失败
                                message.what = MSG_REQUEST_MESSAGE_LIST_FAILE;
                                message.obj = prompt;
                                sendUiMessage(message);
                                if (pageIndex > 0) {
                                    --pageIndex;
                                }
                            }

                        });
                break;
            case MSG_BACK_REQUEST_DELETE:
                sendEmptyUiMessage(MSG_UI_REQUEST_DELETE_START);
                User user1 = UserManager.getInstance().getCurrentUserInternal();
                if (user1 == null) {
                    return;
                }
                long appId = SDKControler.getAppId();
                String pwd = null;
                int source = 0;
                if (TextUtils.isEmpty(user1.getPassword())) {
                    pwd = user1.getKugouToken();
                    source = 1;
                } else {
                    pwd = user1.getPassword();
                    source = 0;
                }
                MyMessage myMessage = (MyMessage) msg.obj;
                UserManager.getInstance().editMessageItem(user1.getAccountName(), "delmessage",
                        String.valueOf(((MyMessage) msg.obj).getMessageid()),
                        myMessage.getPageIndex(), PAGE_SIZE, new OnEditMessageListener() {

                            @Override
                            public void onSuccess() {
                                Message message = new Message();
                                message.what = MSG_UI_REQUEST_DELETE_SUCCESS;
                                message.arg1 = msg.arg1;
                                message.obj = msg.obj;
                                sendUiMessage(message);
                            }

                            @Override
                            public void onFailed(String errorMsg) {
                                Message message = new Message();
                                message.what = MSG_UI_REQUEST_DELETE_FAILE;
                                message.obj = errorMsg;
                                sendUiMessage(message);
                            }
                        });
                break;
        }
    }

    @Override
    public void handleUiMessage(Message msg) {
        switch (msg.what) {
            case MSG_SHOW_LOADING_VIEW:
                if (mListView.getFooterViewsCount() == 0) {
                    mListView.addFooterView(getFooterView());
                }
                // 开始加载数据，显示loading
                showFootProgressBar();
                if (adapter.getCount() == 0) {
                    showLoadingView();
                }
                break;
            case MSG_REQUEST_MESSAGE_LIST_SUCCESS:
                hideFootProgressBar();
                ArrayList<MyMessage> messages = (ArrayList<MyMessage>) msg.obj;

                if (messages != null) {
                    if (messages.size() == 0) {
                        mHasMoreData = false;
                        // 请求的数据如果为空，并且当前没有消息才显示无内容界面
                        if (adapter.getDatas().size() == 0) {
                            showLayoutEmpty();
                        } else {
                            mListView.removeFooterView(footerView);
                        }
                    } else {
                        mLastMessageUnixTime = messages.get(messages.size() - 1).getInserttime();
                        showListView();
                        if (messages.size() < PAGE_SIZE && mListView.getFooterViewsCount() > 0) {
                            mListView.removeFooterView(footerView);
                        }
                        if (messages.size() > 0) {
                            // 数据加载成功,且数据条数不为0
                            adapter.addDatas(messages);
                            adapter.notifyDataSetChanged();
                        } else {
                            if (pageIndex > 0) {
                                pageIndex--;
                            }
                        }
                    }

                }
                break;
            case MSG_REQUEST_MESSAGE_LIST_FAILE:
                // String errorMsg = (String) msg.obj;
                hideFootProgressBar();
                if (adapter.getCount() > 0) {
                    showToast("数据加载失败");
                } else {
                    showLayoutResult();
                    // tvLoadingWrong.setText(errorMsg);
                }
                break;
            case MSG_UI_REQUEST_DELETE_START:
                progressDialog.show();
                break;
            case MSG_UI_REQUEST_DELETE_SUCCESS:
                progressDialog.dismiss();
                adapter.getDatas().remove(msg.arg1);
                adapter.notifyDataSetChanged();
                MyMessage myMessage = (MyMessage) msg.obj;
                if (myMessage.getIsread() == 0) {
                    Intent intent = new Intent(SDKActions.ACTION_DELETE_ONE_UNREAD_EMAIL);
                    intent.putExtra(MSG_ID, myMessage.getMessageid());
                    sendBroadcast(intent);
                }

                if (adapter.getDatas().size() == 0) {
                    showLayoutEmpty();
                } else if (adapter.getDatas().size() < 6 && mHasMoreData) {
                    sendEmptyBackgroundMessage(MSG_REQUEST_MESSAGE_LIST);
                }

                break;
            case MSG_UI_REQUEST_DELETE_FAILE:
                progressDialog.dismiss();
                showToast(msg.obj.toString());
                break;
        }
    }

    private void showLoadingView() {
        mTipsLayout.setVisibility(View.VISIBLE);
        mTipsLayout.show(TipsLayout.TYPE_LOADING);
        layoutEmail.setVisibility(View.GONE);
    }

    private void showListView() {
        mTipsLayout.setVisibility(View.GONE);
        layoutEmail.setVisibility(View.VISIBLE);
    }

    private void showLayoutResult() {
        layoutEmail.setVisibility(View.GONE);
        mTipsLayout.setVisibility(View.VISIBLE);
        mTipsLayout.show(TipsLayout.TYPE_FAILE);
    }

    private void showLayoutEmpty() {
        layoutEmail.setVisibility(View.GONE);
        mTipsLayout.setVisibility(View.VISIBLE);
        mTipsLayout.show(TipsLayout.TYPE_EMPTY_CONTENT);
    }

    private View getFooterView() {
        if (footerView != null) {
            return footerView;
        }
        footerView = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
                Rx.layout.kg_layout_footer_loading, null);
        TextView info = (TextView) footerView.findViewById(Rx.id.kg_loading_tips);
        info.setText("加载更多");
        footerView.findViewById(Rx.id.kg_loading_progress_bar).setVisibility(View.GONE);
        info.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (findViewById(Rx.id.kg_loading_progress_bar).getVisibility() == View.VISIBLE) {
                    return;
                }
                sendEmptyBackgroundMessage(MSG_REQUEST_MESSAGE_LIST);
            }
        });
        return footerView;
    }

    private void showFootProgressBar() {
        TextView text = (TextView) footerView.findViewById(Rx.id.kg_loading_tips);
        text.setText("正在加载...");
        footerView.findViewById(Rx.id.kg_loading_progress_bar).setVisibility(View.VISIBLE);
    }

    private void hideFootProgressBar() {
        TextView text = (TextView) footerView.findViewById(Rx.id.kg_loading_tips);
        text.setText("加载更多");
        footerView.findViewById(Rx.id.kg_loading_progress_bar).setVisibility(View.GONE);
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        View layoutLoading = findViewById(Rx.id.kg_loading_layout);
        if (layoutLoading == null) {
            return;
        }
        // 滚动到底部
        if (scrollState == OnScrollListener.SCROLL_STATE_IDLE
                || scrollState == OnScrollListener.SCROLL_STATE_FLING) {
            if (view.getLastVisiblePosition() >= (view.getCount() - 1)) {
                if (findViewById(Rx.id.kg_loading_progress_bar).getVisibility() == View.VISIBLE) {
                    return;
                }
                sendEmptyBackgroundMessage(MSG_REQUEST_MESSAGE_LIST);
            }
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
            int totalItemCount) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onDelete(int position, MyMessage myMessage) {
        Message msg = new Message();
        msg.what = MSG_BACK_REQUEST_DELETE;
        msg.arg1 = position;
        msg.obj = myMessage;
        sendBackgroundMessage(msg);
    }

    @Override
    public void onMessageItemClick(int position, MyMessage myMessage) {
        Intent intent = new Intent(context, MessageDetailActivity.class);
        intent.putExtra(MSG_ID, adapter.getItem(position).getMessageid());
        intent.putExtra(MSG_POSITION, position);
        intent.putExtra("isread", myMessage.getIsread());
        intent.putExtra("pageIndex", myMessage.getPageIndex());
        startActivityForResult(intent, MESSAGE_DETAILREQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case MESSAGE_DETAILREQUEST_CODE:
                int position = intent.getIntExtra(MSG_POSITION, -1);
                if (position != -1) {
                    adapter.getDatas().remove(position);
                    adapter.notifyDataSetChanged();
                }
                break;
            default:
                break;
        }
    }

    class EmailReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action != null && SDKActions.ACTION_READ_ONE_EMAIL.equals(action)) {
                int position = intent.getIntExtra(MSG_POSITION, -1);
                if (position != -1 && position < adapter.getCount()) {
                    adapter.getItem(position).setIsread(1);
                    adapter.notifyDataSetChanged();
                }
            }
        }
    }

}
